package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.mapper.*;
import com.tanhua.server.pojo.*;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestSouleService {
    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;
    @Autowired
    private QuestionnaireMapper questionnaireMapper;
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;
    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;
    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;
    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    public  List<QuestionnaireListVo> questionnaireList() {

        //获取user
        User user = UserThreadLocal.get();
        //返回的对象
        List<QuestionnaireListVo> resultList = new ArrayList<>();

        //根据用户id查询用户锁表user_question_lock，获取问卷列表id和相对应的锁状态，将结果放入vo中
        QueryWrapper<QuestionUserLock> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("user_id",user.getId());
        List<QuestionUserLock> questionUserLocks = this.questionUserLockMapper.selectList(queryWrapper1);
        for (QuestionUserLock questionUserLock : questionUserLocks) {
            QuestionnaireListVo questionnaireListVo = new QuestionnaireListVo();
            questionnaireListVo.setId(questionUserLock.getQuestionnaireId());
            questionnaireListVo.setIsLock(questionUserLock.getIsLock());
            resultList.add(questionnaireListVo);
        }

        //获取问卷id 123
        List<Long> questionnaireIds = new ArrayList<>();
        for (QuestionUserLock questionUserLock : questionUserLocks) {
            questionnaireIds.add(questionUserLock.getQuestionnaireId());
        }

        //根据获取的问卷id在问卷表questionnaire,查出问卷的信息放入到vo中
        QueryWrapper<Questionnaire> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id",questionnaireIds);
        List<Questionnaire> questionnaireList = this.questionnaireMapper.selectList(queryWrapper2);
        for (Questionnaire questionnaire : questionnaireList) {
            for (QuestionnaireListVo questionnaireListVo : resultList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(questionnaireListVo.getId().toString())){
                    questionnaireListVo.setName(questionnaire.getName());
                    questionnaireListVo.setLevel((questionnaire.getLevel().toString()));
                    questionnaireListVo.setStar(questionnaire.getStar());
                    questionnaireListVo.setCover(questionnaire.getCover());
                }
            }
        }
        //将问题和问题选项填充到vo中
        for (QuestionnaireListVo questionnaireListVo : resultList) {
            QueryWrapper<SoulQuestion> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("questionnaire_id",questionnaireIds);
            List<SoulQuestion> soulQuestionList = soulQuestionMapper.selectList(queryWrapper3);
            List<SoulQuestionsVo> soulQuestionsVos = new ArrayList<>();
            for (SoulQuestion soulQuestion : soulQuestionList) {
                //填充soulQuestionVo
                SoulQuestionsVo soulQuestionsVo = new SoulQuestionsVo();
                soulQuestionsVo.setId(soulQuestion.getId().toString());
                soulQuestionsVo.setQuestion(soulQuestion.getStem());
                soulQuestionsVos.add(soulQuestionsVo);
                //填充soulQuestionVo的option选项
                QueryWrapper<SoulQuestionOption> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("question_id",soulQuestion.getId());
                List<SoulQuestionOption> soulQuestionOptions = soulQuestionOptionMapper.selectList(queryWrapper4);
                List<SoulQuestionsOptionsVo> soulQuestionsOptionsVos = new ArrayList<>();
                for (SoulQuestionOption soulQuestionOption : soulQuestionOptions) {
                    SoulQuestionsOptionsVo soulQuestionsOptionsVo = new SoulQuestionsOptionsVo();
                    soulQuestionsOptionsVo.setId(soulQuestionOption.getId().toString());
                    soulQuestionsOptionsVo.setOption(soulQuestionOption.getContent());
                    soulQuestionsOptionsVos.add(soulQuestionsOptionsVo);
                }
                soulQuestionsVo.setOptions(soulQuestionsOptionsVos);
            }
            questionnaireListVo.setQuestions(soulQuestionsVos);
        }

        return resultList;
    }

    public void submitQuestions(List<Answers> answersList) {
        Integer score = 0;
        Long questionId = 0L;

        //计算分数
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();
            Long optionId = answers.getOptionId();
            QueryWrapper queryWrapper = new QueryWrapper();
            //queryWrapper.eq("question_id", questionId);
            queryWrapper.eq("id", optionId);
            SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(queryWrapper);
            score += Integer.parseInt(soulQuestionOption.getScore());
        }

        System.out.println(score);

        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();

        //默认初级开启
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper();
        if (questionnaireId<=2){
            queryWrapper.eq("questionnaire_id", questionnaireId+1);
            QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
            if(questionUserLock.getIsLock().equals(1)){
                questionUserLock.setIsLock(0);
                questionUserLockMapper.update(questionUserLock,queryWrapper);
            }
        }
        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        QueryWrapper<QuestionnaireResult> query3 = new QueryWrapper<>();
        query3.eq("questionnaire_id", questionnaireId);
        List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(query3);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get().getId());
        questionnaireReport.setQuestionnaireId(questionnaireId);
        for (QuestionnaireResult questionnaireResult : questionnaireResults) {
            String[] split = questionnaireResult.getScope().split(",");
            if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                questionnaireReport.setResultId(questionnaireResult.getId());
                break;
            }
        }
        questionnaireReportMapper.insert(questionnaireReport);
    }

    public TestResultVo testResult(Long id) {
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //通过id获取报告里面的数据
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);
        Long resultId = questionnaireReport.getResultId();
        //通过报告表里面的resultId查询数据，写维度集合里
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(resultId);
        dimensionList.add(new Dimensions("extroversion",questionnaireResult.getExtroversion()));
        dimensionList.add(new Dimensions("judgement",questionnaireResult.getJudgement()));
        dimensionList.add(new Dimensions("abstraction",questionnaireResult.getAbstraction()));
        dimensionList.add(new Dimensions("rationality",questionnaireResult.getRationality()));

        //保存到testResultVo里面
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        testResultVo.setDimensions(dimensionList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        QueryWrapper<QuestionnaireReport> queryWrapper = new QueryWrapper();
        queryWrapper.eq("result_id",resultId);
        List<QuestionnaireReport> questionnaireReports = questionnaireReportMapper.selectList(queryWrapper);
        List<Long> userIds = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            userIds.add(report.getUserId());
        }


        //查询所有用户的完整信息
        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper();
        queryWrapper1.in("user_id",userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper1);

        ArrayList<SimilarYou> similarYouList = new ArrayList<>();
        //如果是当前用户就跳过，否则添加到相似的人集合里
        for (UserInfo userInfo : userInfos) {
            if(UserThreadLocal.get().getId().equals(userInfo.getUserId())){
                continue;
            }
            similarYouList.add(new SimilarYou(userInfo.getUserId(),userInfo.getLogo()));
        }

        testResultVo.setSimilarYou(similarYouList);
        return testResultVo;
    }
}
